package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public User findUserByUsername(String username) {

        User user = userMapper.findUserByUsername(username);
        //根据user的id查询user和role的关联表,得到roleId,再查询role表得到相应的角色并封装成set集合
        //判空
        if (user == null){
            return null;
        }
        Integer id = user.getId();
        Set<Role> set = roleMapper.findRoleByUid(id);
        if (set != null && set.size() > 0){
            //遍历,根据roleid查询权限permission
            for (Role role : set) {
                Integer roleId = role.getId();
                Set<Permission> sp = permissionMapper.findPermissionById(roleId);
                //谨记,集合和对象在使用前,一定要进行判空,不然容易空指针
                if (sp != null && sp.size() > 0){
                    role.setPermissions(sp);
                }
            }
            user.setRoles(set);
        }
        return user;
    }
}
